package com.migration.controller;

import com.migration.generator.ModelGenerator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据库模型生成控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/migration/model")
@Tag(name = "数据库模型生成接口", description = "提供数据库模型生成功能")
public class MigrationModelController {

    private final ModelGenerator modelGenerator;

    /**
     * 生成旧库模型
     *
     * @param excludePrefixes 排除的表前缀，多个前缀以逗号分隔，默认为"onl_,qrtz_,sds_"
     * @return 结果
     */
    @PostMapping("/generate/old")
    @Operation(
            summary = "生成旧库模型",
            description = "根据配置生成旧数据库的实体模型",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "生成成功",
                            content = @Content(mediaType = "application/json",
                                    schema = @Schema(implementation = Map.class))
                    ),
                    @ApiResponse(
                            responseCode = "400",
                            description = "生成失败",
                            content = @Content(mediaType = "application/json")
                    )
            }
    )
    public ResponseEntity<Map<String, Object>> generateOldDbModels(@RequestParam(value = "excludePrefixes", defaultValue = "onl_,qrtz_,sds_") String excludePrefixes) {
        try {
            log.info("开始生成旧库模型，排除前缀: {}...", excludePrefixes);

            // 将排除前缀字符串转换为列表
            Map<String, Object> config = getStringObjectMap(excludePrefixes);

            Map<String, Object> result = modelGenerator.generateOldDbModels(config);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成旧库模型失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 生成新库模型
     *
     * @param excludePrefixes 排除的表前缀，多个前缀以逗号分隔，默认为"onl_,qrtz_,sds_"
     * @return 结果
     */
    @PostMapping("/generate/new")
    @Operation(
            summary = "生成新库模型",
            description = "根据配置生成新数据库的实体模型",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "生成成功",
                            content = @Content(mediaType = "application/json",
                                    schema = @Schema(implementation = Map.class))
                    ),
                    @ApiResponse(
                            responseCode = "400",
                            description = "生成失败",
                            content = @Content(mediaType = "application/json")
                    )
            }
    )
    public ResponseEntity<Map<String, Object>> generateNewDbModels(@RequestParam(value = "excludePrefixes", defaultValue = "onl_,qrtz_,sds_") String excludePrefixes) {
        try {
            log.info("开始生成新库模型，排除前缀: {}...", excludePrefixes);

            // 将排除前缀字符串转换为列表
            Map<String, Object> config = getStringObjectMap(excludePrefixes);

            Map<String, Object> result = modelGenerator.generateNewDbModels(config);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成新库模型失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 生成所有模型
     *
     * @param excludePrefixes 排除的表前缀，多个前缀以逗号分隔，默认为"onl_,qrtz_,sds_"
     * @return 结果
     */
    @PostMapping("/generate/all")
    @Operation(
            summary = "生成所有模型",
            description = "生成新旧数据库的实体模型，可以传入需要排除的表前缀",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "生成成功",
                            content = @Content(mediaType = "application/json",
                                    schema = @Schema(implementation = Map.class))
                    ),
                    @ApiResponse(
                            responseCode = "400",
                            description = "生成失败",
                            content = @Content(mediaType = "application/json")
                    )
            }
    )
    public ResponseEntity<Map<String, Object>> generateAllModels(@RequestParam(value = "excludePrefixes", defaultValue = "onl_,qrtz_,sds_") String excludePrefixes) {
        try {
            log.info("开始生成所有模型，排除前缀: {}", excludePrefixes);

            // 将排除前缀字符串转换为列表
            Map<String, Object> config = getStringObjectMap(excludePrefixes);

            Map<String, Object> result = new HashMap<>();

            log.info("生成旧库模型...");
            Map<String, Object> oldResult = modelGenerator.generateOldDbModels(config);
            result.put("oldDb", oldResult);

            log.info("生成新库模型...");
            Map<String, Object> newResult = modelGenerator.generateNewDbModels(config);
            result.put("newDb", newResult);

            result.put("success", true);
            result.put("message", "成功生成所有模型");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("生成所有模型失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 将排除前缀字符串转换为列表
     *
     * @param excludePrefixes
     * @return
     */
    private static Map<String, Object> getStringObjectMap(String excludePrefixes) {
        // 将排除前缀字符串转换为列表
        List<String> excludePrefixList = Arrays.stream(excludePrefixes.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());

        Map<String, Object> config = new HashMap<>();
        config.put("tablePrefix", "");  // 默认无表前缀
        config.put("excludePrefixes", excludePrefixList);
        return config;
    }
}
